<?php

namespace app\api\service\shanghui;

use app\api\service\Basics;
use app\api\model\shanghui\Order as OrderModel;
use app\common\enum\recharge\order\PayStatus as PayStatusEnum;
use think\Db;
class PaySuccess extends Basics
{
    // 订单模型
    public $model;

    // 当前用户信息
    private $user;

    /**
     * 构造函数
     * PaySuccess constructor.
     * @param $orderNo
     * @throws \think\exception\DbException
     */
    public function __construct($orderNo,$pay_status='')
    {
        // 实例化订单模型
        $this->model = OrderModel::getPayDetail($orderNo,$pay_status);
        $this->wxappId = $this->model['wxapp_id'];
    }

    /**
     * 获取订单详情
     * @return OrderModel|null
     */
    public function getOrderInfo()
    {
        return $this->model;
    }

    /**
     * 订单支付成功业务处理
     * @param array $payData 支付回调数据
     * @return bool
     */
    public function onPaySuccess($payType, $payData = [])
    {
        Db::startTrans();
        try {
            if($payType == 20){
                // 更新订单状态-微信支付
                Db::name("shanghui_order")
                    ->where('pay_status',PayStatusEnum::PENDING)
                    ->where('order_no',$this->model['order_no'])
                    ->update([
                        'pay_status' => PayStatusEnum::SUCCESS,
                        'pay_time' => time(),
                        'transaction_id' => $payData['transaction_id']
                ]);
            }
           
            // 商会人数购买一年有效期 
            $end_time = date('Y-m-d',strtotime('+1 year'));
            // 商会人数累加
            $state = Db::name("shanghui")->where('id',$this->model['shanghui_id'])->inc("people",$this->model['peoplenumber'])->update();
            $info = Db::name("shanghui")->where('id',$this->model['shanghui_id'])->find();
            if(!$info['end_date']){
                Db::name("shanghui")->where('id',$this->model['shanghui_id'])->update(['end_date'=>$end_time]); //更新有效期
            }
            
            // 累计费用
            if($this->model['plan_id'] ==2){
                if($info['auth'] ==0){
                    Db::name("shanghui")->where('id',$this->model['shanghui_id'])->update(['auth'=>1]);
                }
                Db::name("shanghui")->where('id',$this->model['shanghui_id'])->inc("cost",$this->model['pay_price'])->update();
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }

}